import API from "@/api";
import type { ILessonResult } from "@/pages/lowPricedCourse/trialCourseHome/courseList/index.vue";

interface ISceneSpeakResult {
  scoreLimit: number;
  sceneSpeak: ISceneSpeak;
}

export interface ISceneSpeak {
  img: string;
  uk_voice: string;
  us_voice: string;
  sentences: string;
  sentences_bh: string;
  scene_speak_id: number;
  user_voice?: string;
  option: ISceneOption[];
}

export interface ISceneOption {
  img: string;
  sentences: string;
  sentences_bh: string;
  scene_speak_id: number;
  user_voice?: string;
  score: number;
  list?: ISceneQuestion;
}

export interface ISceneQuestion {
  img: string;
  uk_voice: string;
  us_voice: string;
  sentences: string;
  sentences_bh: string;
  scene_speak_id: number;
  user_voice?: string;
  option: ISceneOption[];
  level: number;
}

export interface ISceneSpeakLesson {
  isRelearn: boolean;
  isNeedLaunchPage: boolean;
  data: {
    questions: ISceneSpeak,
    stepLength: number;
    currentQuestionIndex: number;
    scoreLimit: number;
  }
}

export const requestSceneSpeakData = (sectionId: number): Promise<ILessonResult> => {
  return new Promise((resolve, reject) => {
    API.sceneSpeak({ section_id: sectionId }).then(res => {
      let result = res as ISceneSpeakResult;
      let scoreLimit = result.scoreLimit;

      const handleInitOption = (data: ISceneSpeak) => {
        let stepLength = 0;
        let isRelearn = false;

        const handleSetStep = (obj: ISceneSpeak, step: number): number => {
          if (Array.isArray(obj.option) && obj.option.length > 0) {
            const firstOption = obj.option[0];
            step += 1;

            if (firstOption.list) {
              return handleSetStep(firstOption.list, step);
            }
          }
          return step;
        };

        const findLastOptionArray = (obj: ISceneSpeak, lastOptionArray: ISceneOption[]) => {
          if (obj.option && Array.isArray(obj.option)) {
            for (let i = 0, len = obj.option.length; i < len; i++) {
              const item = obj.option[i];

              if (item.list) {
                findLastOptionArray(item.list, lastOptionArray);
              } else {
                lastOptionArray.push(item);
              }
            }

            return lastOptionArray;
          }
        };

        const findCurrentIndex = (obj: ISceneSpeak, parent: AnyObject, currentIndex: number, isEmpty: boolean): any => {
          if (obj.option && Array.isArray(obj.option)) {
            for (let i = 0, len = obj.option.length; i < len; i++) {
              const item = obj.option[i];

              if (item.user_voice) {
                isEmpty = false;
                parent = item;
                currentIndex += 1;

                if (item.list) {
                  return findCurrentIndex(item.list, item, currentIndex, isEmpty);
                }
              }
            }

            return {
              isEmpty,
              currentIndex,
              parent: isEmpty ? parent : parent.list,
            }
          }
        }

        const clearUserVoice = (obj: ISceneSpeak) => {
          for (let key in obj) {
            if (obj.hasOwnProperty(key)) {
              // @ts-ignore
              if (typeof obj[key] === "object" && obj[key] !== null) {
                // @ts-ignore
                clearUserVoice(obj[key]);
              } else if (key === "user_voice") {
                obj[key] = "";
              }
            }
          }

          return {
            data,
            isRelearn,
            stepLength,
            isEmpty: true,
            currentIndex: 0,
          }
        };

        stepLength = handleSetStep(data, 0);
        const lastOptionArray = findLastOptionArray(data, []) as ISceneOption[];

        isRelearn = lastOptionArray.some(item => item.user_voice && item.user_voice.length > 0);

        if (isRelearn) {
          return clearUserVoice(data);
        } else {
          const { parent, currentIndex, isEmpty } = findCurrentIndex(data, data, 0, true);

          return {
            isEmpty,
            isRelearn,
            stepLength,
            data: parent,
            currentIndex,
          }
        }
      }

      const { isRelearn, stepLength, data, currentIndex, isEmpty } = handleInitOption(result.sceneSpeak);

      let resolveData: ILessonResult = {
        isRelearn,
        isNeedLaunchPage: isEmpty || isRelearn,
        data: {
          questions: data,
          stepLength,
          currentQuestionIndex: currentIndex,
          scoreLimit: scoreLimit,
        }
      }

      console.log("resolveData", resolveData);

      resolve(resolveData);
    }).catch(() => {
      reject();
    })
  })
}